﻿using System;
using System.ComponentModel;
using System.Timers;
using Devv.FreshTracker.Entity;

namespace Devv.FreshTracker
{
	public class SessionTimer
	{
		#region Events

		public delegate void TimerEventHandler(TimeSpan ts);

		public static event TimerEventHandler OnTimerTick;
		public static event TimerEventHandler OnTimerAutoStop;

		#endregion

		#region Internal roperties

		private static Timer Timer { get; set; }
		private static Session CurrentSession { get; set; }

		#endregion

		#region External properties

		public static Int32 Seconds
		{
			get
			{
				return CurrentSession.TempSeconds;
			}
		}

		public static Boolean Running
		{
			get
			{
				return Timer.Enabled;
			}
		}

		#endregion

		#region Load and thread safety

		public static void Load()
		{
			Timer = new Timer {Interval = 1000, Enabled = false};
			Timer.Elapsed += Timer_Elapsed;

			CurrentSession = new Session();
		}

		public static void ThreadSync(ISynchronizeInvoke thread)
		{
			Timer.SynchronizingObject = thread;
		}

		#endregion

		#region Public methods

		public static void Reset()
		{
			Timer.Stop();

			CurrentSession.TempSeconds = 0;

			Maintenance.Log("Reset session timer.");
		}

		public static void Start()
		{
			Timer.Start();

			Maintenance.Log("Started session timer.");
		}

		public static void Pause()
		{
			Timer.Stop();

			Maintenance.Log("Paused session timer.");
		}

		public static void PreSave(Task task)
		{
			Pause();

			CurrentSession.Task = task;
			CurrentSession.SetHoursFromSeconds(CurrentSession.TempSeconds);
		}

		public static void Save(String notes)
		{
			CurrentSession.Notes = notes;

			LocalCache.UploadSession(CurrentSession);

			CurrentSession = new Session();
		}

		#endregion

		#region Internal implementation

		private static void Timer_Elapsed(Object sender, ElapsedEventArgs e)
		{
			CurrentSession.TempSeconds++;

			TimeSpan ts = TimeSpan.FromSeconds(CurrentSession.TempSeconds);

			OnTimerTick(ts);

			if (Options.AutoStop > 0 && Convert.ToDouble(CurrentSession.TempSeconds) / 60 >= Options.AutoStop)
			{
				Pause();
				OnTimerAutoStop(ts);
			}
		}

		#endregion
	}
}